# -*- coding: utf-8 -*-

import pytest

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService

import time
import datetime

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
def create_appium_session_by_api(custom_opts = None):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options)


def test_app_capability_explicit_intent(start_appium_service):
    driver = create_appium_session_by_api()
    driver.start_activity("com.google.android.dialer", ".extensions.GoogleDialtactsActivity")

def test_app_capability_appWaitActivity(start_appium_service):
    custom_opts = {
        "appium:appWaitPackage": "com.google.android.apps.messaging",
        "appium:appWaitActivity": ".ui.ConversationListActivity",
    }
    driver = create_appium_session_by_api(custom_opts)
    assert driver.current_activity == custom_opts["appium:appWaitActivity"]

def test_app_capability_closeAppAfterSession(start_appium_service):
    custom_opts = {
        "appium:noReset": True,
        "appium:appPackage": "com.google.android.apps.messaging",
        "appium:appActivity": ".ui.ConversationListActivity",

        "appium:shouldTerminateApp": True
    }
    driver = create_appium_session_by_api(custom_opts)
    assert driver.current_activity == custom_opts["appium:appActivity"]
    driver.quit()

    # 被测应用在上一步会话退出时已经被关闭了
    driver = create_appium_session_by_api({"appium:noReset": True})
    assert driver.current_activity != custom_opts["appium:appActivity"]
